import { Injectable, ForbiddenException } from '@nestjs/common'
import { Model } from 'mongoose'
import { InjectModel } from '@nestjs/mongoose'
import { Role } from './schemas/role.schema'
import { RoleDto } from './dto/role.dto'
import { CreateRoleDto } from './dto/create-role.dto'
import { randomUUID } from 'node:crypto'

@Injectable()
export class RolesService {
  constructor(@InjectModel(Role.name) private roleModel: Model<Role>) {}

  async insertMany(Data: CreateRoleDto[]): Promise<any> {
    for (const item of Data) {
      const roleInfo = await this.roleModel
        .findOne({
          name: item.name
        })
        .exec()
      if (roleInfo) throw new ForbiddenException('角色已存在')
      else {
        const role: any = item
        if (!role.id) role.id = randomUUID()
      }
    }
    const createdRole = this.roleModel.insertMany(Data)
    return createdRole
  }

  async find(): Promise<Role[]> {
    return this.roleModel.find({ name: /^(?!admin)/ }).exec()
  }

  async findOne(data: RoleDto): Promise<Role | null> {
    return this.roleModel.findOne(data).exec()
  }

  async updateOne(data: any) {
    Reflect.deleteProperty(data, '_id')
    return this.roleModel.updateOne({ id: data.id }, { $set: data }).exec()
  }

  async deleteOne(data: any) {
    if (data) {
      const deletedRole = await this.roleModel.deleteOne(data).exec()
      return deletedRole
    }
  }

  async initRoles() {
    const data: any = { name: 'admin' }

    const roleInfo: any = await this.findOne(data)
    if (!roleInfo) {
      return (
        await this.insertMany([
          {
            name: data.name,
            pid: '',
            menus: []
          }
        ])
      )[0]
    } else return roleInfo
  }
}
